﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using md.imi.membrane.common;
using md.imi.membrane.common.Interfaces;
using md.imi.membrane.common.Messaging;
using md.imi.membranes.objects.psystems;

namespace md.imi.membranes.objects
{
    /// <summary>
    ///     Holds current workspace related information
    /// </summary>
    public class WorkSpace 
    {

        private static WorkSpace    _instance = null;
        private PSystemsTree        _pSystemTree = null;
        private MessagesManager     _messagesManager = null;
        

        /// <summary>
        ///     A list of active projects tree. Why it is a list of ress.
        /// List contains all initially created by the user (user intervention at list) projects.
        /// But tree is used to sore a possible evaluation of a concrete inially pSystem
        /// </summary>
        public List<PSystemsTree> Projects { get; set; }

        /// <summary>
        ///     the currently selected p system in workspace
        /// </summary>
        public PSystemsTree SelectedProject 
        {
            get {return _pSystemTree;}
            set {_pSystemTree= value; }
        }


        /// <summary>
        ///     Default constructor is private
        /// </summary>
        private WorkSpace ()
        {
            Projects = new List<PSystemsTree>();
            _messagesManager = new MessagesManager();

            // SelectePSystem = new PSystem();
        }

        [XmlIgnore]
        public MessagesManager MessagesManager
        {
            get { return _messagesManager; }
        }

        /// <summary>
        ///     Singletone copy of this class
        /// </summary>
        [XmlIgnore]
        public static WorkSpace Instance
        {
            get
            {
                if ( _instance == null ) _instance = new WorkSpace();
                return _instance;
            }

        }

        #region Serialization 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName"></param>
        public void ExportToXml(string fileName)
        {
            TextWriter textWriter = null;

            try
            {
                Type type = SelectedProject.GetType();
                XmlSerializer xmlSerializer = new XmlSerializer(type);
                textWriter = new StreamWriter(fileName);
                xmlSerializer.Serialize(textWriter, SelectedProject);
            }
            catch (Exception ex)
            {
                ex.Source = String.Format("Cannot serialize XML file : {0} ", ex.Source); 
                Logger.Instance.Error(ex);

                throw;
            }
            finally
            {
                if (textWriter != null)
                {
                    textWriter.Close();
                }
            }
        }

        public PSystemsTree ImportFromXml(out PSystemsTree target, string fileName)
        {
            #region Check parameters
            
            if (String.IsNullOrEmpty(fileName))
            {
                throw new Exception("Source file name not indicated");
            }
            
            if (!File.Exists(fileName))
            {
                throw new Exception(String.Format("File {0} does not exist!", fileName));
            }
            #endregion
         
            TextReader textReader = null;
            // TODO: After deserialization, setup parent p-systems
            try
            {
                target = null;
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(PSystemsTree));
                textReader = new StreamReader(fileName);
                target = (PSystemsTree)xmlSerializer.Deserialize(textReader);
                target.ProjectFileName = fileName;
                return target;
            }
            catch (FileNotFoundException ex)
            {
                Logger.Instance.Error(ex);
                throw new Exception(string.Format("File '{0}' couldn't be found", fileName));
            }
            catch (Exception ex)
            {
                Logger.Instance.Error(ex);
                throw new Exception(String.Format("Failed to deserialize XML : {0}", ex.Message));
            }
            finally
            {
                if (textReader != null)
                {
                    textReader.Close();
                }
            }
        }
        
        /// <summary>
        ///     Load a new copy of this object from XML file
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public PSystemsTree ImportFromXml(string fileName)
        {
            return ImportFromXml(out _pSystemTree, fileName);
        }
        #endregion
    }
}
